import axios from 'axios'
import {useUserStore} from "@/stores/userStore.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

// 创建axios实例
const http = axios.create({
    //baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    baseURL: 'http://localhost:8888/api',
    timeout: 500000
})

// axios请求拦截器
// 一般会进行token身份验证等
http.interceptors.request.use(config => {
    const userStore = useUserStore();
    //console.log(token)
    if(userStore.userInfo){
        const token = userStore.userInfo.token;
        config.headers.Authorization = `${token}`
    }
    return config
}, e => Promise.reject(e))

// axios响应式拦截器
// 一般进行错误的统一提示，token失效的处理等
http.interceptors.response.use(res => {
    if(res.data.code !== 200){
        if(res.data.description) {
            ElMessage.error(res.data.description)
        }else{
            ElMessage.error(res.data.message)
        }
    }
    console.log("res",res)
    return res.data
}, e => {
    console.log(e)
    //401token失效处理
    const userStore = useUserStore();
    if(e.response.status === 401){
        userStore.clearUserInfo()
        //ElMessage.error("登录过期，请重新登录")
        router.push('/login')
    }
    return Promise.reject(e)
})


export default http